import 'package:flutter/material.dart';
import 'package:flutterdemo/pages/search_page.dart';
import 'package:flutterdemo/plugin/asr_manager.dart';
import 'package:flutterdemo/util/navigator_util.dart';

class SpeakPage extends StatefulWidget {
  const SpeakPage({Key? key}) : super(key: key);

  @override
  State<SpeakPage> createState() => _SpeakPageState();
}

  //动画构造器 SingleTickerProviderStateMixin
  //当widget不显示时，动画定时器将会暂停，
  // 当widget再次显示时，动画定时器重新恢复执行，这样就可以避免动画相关UI不在当前屏幕时消耗资源
class _SpeakPageState extends State<SpeakPage>
    with SingleTickerProviderStateMixin {

  String speakTips = '长按说话';
  String speakResult = '';
  late Animation<double> animation;
  late AnimationController controller;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000));
    animation = CurvedAnimation(parent: controller, curve: Curves.easeIn)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
            controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
            controller.forward();
        }
      });
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.all(30),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[_topItem(), _bottomItem()],
          ),
        ),
      ),
    );
  }

  _topItem() {
    return Column(
      children:  <Widget>[
        const Padding(
          padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
          child: Text('你可以这样说',
              style: TextStyle(fontSize: 16, color: Colors.black54))),
        const Text('故宫门票\n北京一日游\n迪士尼乐园',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 15,
            color: Colors.grey,
          )),
        Padding(
            padding: const EdgeInsets.all(20),
            child: Text(
              speakResult,
              style: const TextStyle(color: Colors.blue),
            ),
        )
      ],
    );
  }

  _bottomItem() {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Stack(
        children: <Widget>[
          GestureDetector(
            onTapDown: (e) {
              _speakStart();
            },
            onTapUp: (e) {
              _speakStop();
            },
            onTapCancel: () {
              _speakStop();
            },
            child: Center(
              child: Column(
                children: <Widget>[
                  Padding(
                      padding: const EdgeInsets.all(10),
                      child: Text(
                        speakTips,
                        style: const TextStyle(color: Colors.blue, fontSize: 12),
                      ),
                  ),
                  Stack(
                    children: <Widget>[
                      Container(
                        height: MIC_SIZE,
                        width: MIC_SIZE,
                      ),
                      Center(
                        child: AnimatedMic(
                          animation,
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
          ),
          Positioned(
              right: 0,
              bottom: 20,
              child: GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                },
                child: const Icon(
                  Icons.close,
                  size: 30,
                  color: Colors.grey,
                ),
              ),
          )
        ],
      ),
    );
  }

  //语音录制开始
   _speakStart() {
      controller.forward();
      setState(() {
        speakTips = '-  识别中  -';
      });
      AsrManager.start().then((text) {
        if (text?.isNotEmpty ?? false) {
          setState(() {
            speakResult = text!;
          });
          Navigator.pop(context);
          NavigatorUtil.push(
              context,
              SearchPage(
                keyword: speakResult,
              ));
          print('----------------' + text!);
        }
      }).catchError((e) {
        print('----------------' + e.toString());
      });

   }
  //语音录制结束
   _speakStop() {
      setState(() {
        speakTips = '长按说话';
      });
      controller.reset();
      controller.stop();
      AsrManager.stop();
   }
}

const double MIC_SIZE  = 80;

class AnimatedMic extends AnimatedWidget {
  static final _opacityTween = Tween<double>(begin: 1, end: 0.5);
  static final _sizeTween = Tween<double>(begin: MIC_SIZE, end: MIC_SIZE - 20);

  AnimatedMic(Animation<double> animation, {Key? key})
        : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable as Animation<double>;

    return Opacity(
        opacity: _opacityTween.evaluate(animation),
        child: Container(
          height: _sizeTween.evaluate(animation),
          width: _sizeTween.evaluate(animation),
          decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.circular(MIC_SIZE / 2),
          ),
          child: const Icon(
            Icons.mic,
            color: Colors.white,
            size: 30,
          ),
        ),
    );
  }
}
